/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package biofilter.filters;

import biofilter.exceptions.InvalidRecordException;
import biofilter.records.FileNameRecord;
import biofilter.records.Record;
import biofilter.util.ProcessHandler;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 * This class is not meant to be used for anything other than an example of how
 * to build a filter that has as it's primary function to run a system command.
 * @author Thomas S. Brettin
 */
public class SystemCommandFilter extends SimpleFilter {

    @Override
    protected Record transformRecord(Record r) throws InvalidRecordException {
        StringBuffer stdOut = null;
        StringBuffer stdErr = null;

        try {
            this.transformedRecord = null;
            if (!(r instanceof FileNameRecord)) {
                throw new RuntimeException("type mismatch, expected FileNameRecord");
            }
            String command = "ls -l " + r.get();
            stdOut = new StringBuffer();
            stdErr = new StringBuffer();
            int pid = ProcessHandler.runCommand(command, stdOut, stdErr);

        } catch (IOException ex) {
            Logger.getLogger(SystemCommandFilter.class.getName()).log(Level.SEVERE, null, ex);
            throw new InvalidRecordException (ex.getMessage());
        } catch (InterruptedException ex) {
            Logger.getLogger(SystemCommandFilter.class.getName()).log(Level.SEVERE, null, ex);
            throw new InvalidRecordException(ex.getMessage());
        }

        Logger.getLogger(SystemCommandFilter.class.getName()).log(Level.INFO, stdOut.toString());
        return new FileNameRecord(stdOut.toString());
    }

    public Record peek() throws InvalidRecordException {
        throw new UnsupportedOperationException("Not supported yet.");
    }
}
